package it.okkam.longwell.ui.command;

import it.okkam.webid.model.DataModel;

import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.ServletContext;

import org.apache.log4j.Logger;
import org.apache.velocity.VelocityContext;

import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import edu.mit.simile.longwell.LongwellServer;
import edu.mit.simile.longwell.login.CheckLogin;
import edu.mit.simile.longwell.ui.FlairMessage;
import edu.mit.simile.longwell.ui.FlairURL;
import edu.mit.simile.longwell.ui.InjectionManager;
import edu.mit.simile.longwell.ui.command.CommandBase;



public class EnableUsersToAdminCommand extends CommandBase {
	final static private Logger s_logger = Logger.getLogger(EnableUsersToAdminCommand.class);
	CheckLogin check=null;
	Model model ;
	public static boolean userInput = false;
	VelocityContext vcContext = null;
	private static String[] usersListToEnable;
	protected ServletContext context;
	/**
	 * @param injectionManager
	 */
	public EnableUsersToAdminCommand(InjectionManager injectionManager) {
		super(injectionManager);
	}

	/* (non-Javadoc)
	 * @see edu.mit.simile.flair.IFlairCommand#execute(edu.mit.simile.flair.FlairMessage)
	 */

	public void execute(FlairMessage msg) throws ServletException {
		usersListToEnable = msg.m_request.getParameterValues("fromUsersToAdministrator");
		if(usersListToEnable!=null && usersListToEnable.length>0){
			for(int i=0;i<usersListToEnable.length;i++){
				enableUsersToAdmin(msg,usersListToEnable[i]);
			}
		}
		try {
			msg.m_response.sendRedirect(new FlairURL(msg).changeCommandQuery("administration_users","").toURLString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


	public void enableUsersToAdmin(FlairMessage msg, String user){
		DataModel datamodel = new DataModel();
		model = LongwellServer.getModelForAuthentication();	
		
		
		String queryString =

		"PREFIX foaf: <http://xmlns.com/foaf/0.1/> "
				+ "PREFIX : <http://www.semanticweb.org/ontologies/2011/9/Rivela-Flussi.owl#> "
				+ "SELECT ?sub " + "WHERE {"
				+ "      ?sub foaf:nickname  \"" + user+ "\" . }";

		Query query = QueryFactory.create(queryString);

		QueryExecution qe = QueryExecutionFactory.create(query, model);
		ResultSet results = qe.execSelect();

		String subject="";
		while (results.hasNext()) {
			QuerySolution member = results.next();
			subject = member.get("sub").toString();
		}
		qe.close();
		StmtIterator it = model.listStatements();
		String prefixPending = "http://www.semanticweb.org/ontologies/2011/9/Rivela-Flussi.owl#rivela_user";
		Statement statemetToRemove=null;
		//remove the user from the pending group
		while(it.hasNext()){
			Statement statement = it.next();
			Resource sub = statement.getSubject();
			Property prop = statement.getPredicate();
			RDFNode pred = statement.getObject();
			//System.out.println(sub.toString() +" "+prop.toString()+" "+pred.toString());
			if(sub.toString().equals(prefixPending))
				if(prop.toString().equals("http://xmlns.com/foaf/0.1/member"))
					if( pred.toString().equals(subject)){
						statemetToRemove = statement;
						break;
			}		
		}
		
		if(statemetToRemove!=null){
			//model.remove(statemetToRemove);
			//datamodel.writeOutPutModel(msg, model);
			//add the user in the rivela_admin
			String riv= "http://www.semanticweb.org/ontologies/2011/9/Rivela-Flussi.owl#";
			String foaf = "http://xmlns.com/foaf/0.1/";
			Resource rivela_user = model.createResource(riv+"rivela_admin");
			Property member = model.createProperty(foaf,"member");
			Resource userResource = model.createResource(subject);
			rivela_user.addProperty(member,userResource);
			datamodel.writeOutPutModel(msg, model);
		}
	}
}